<template>
    <div class="user-center">
        <el-container>
            <el-aside width="200px">
                <div class="back">
                    <span @click="backToHome"><el-icon><Back/></el-icon>返回</span>
                </div>
                <el-menu
                    default-active="1"
                    class="menu"
                    @select="handleSelect">
                    <el-menu-item index="1">
                        <el-icon><User /></el-icon>
                        <span>个人信息</span>
                    </el-menu-item>
                    <el-menu-item index="2">
                        <el-icon><List /></el-icon>
                        <span>预约记录</span>
                    </el-menu-item>
                    <el-sub-menu index="3" default-active="3-1">
                        <template #title>
                            <el-icon><Setting /></el-icon>
                            <span>账号设置</span>
                        </template>
                        <el-menu-item index="3-1">
                            <el-icon><Edit /></el-icon>
                            <span>信息设置</span>
                        </el-menu-item>
                        <el-menu-item index="3-2">
                            <el-icon><Key /></el-icon>
                            <span>密码修改</span>
                        </el-menu-item>
                    </el-sub-menu>
                </el-menu>
            </el-aside>
            <el-main>
                <div class="content" v-loading="loading">
                    <!-- 个人信息 -->
                    <div v-if="activeIndex === '1'" class="profile">
                        <el-descriptions title="个人信息" :column="2" border>
                            <el-descriptions-item label="姓名">{{ user.name }}</el-descriptions-item>
                            <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
                            <el-descriptions-item label="性别">{{ gender }}</el-descriptions-item>
                            <el-descriptions-item label="手机号">{{ user.phone }}</el-descriptions-item>
                            <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
                            <el-descriptions-item label="生日">{{ moment.tz(user.birthday, 'UTC').tz('Asia/Shanghai').format('YYYY-MM-DD') }}</el-descriptions-item>
                            <el-descriptions-item label="注册时间">{{ user?.create_at?.slice(0,10) || '-' }}</el-descriptions-item>
                        </el-descriptions>  
                    </div>
                    
                    <!-- 预约记录 -->
                    <div v-if="activeIndex === '2'" class="appointments" style="height: 400px; overflow-y: auto;">
                        <el-table :data="appointments" style="width: 100%">
                            <el-table-column prop="appointment_date" label="预约日期" width="170">
                                <template #default="{ row }">
                                    {{ row.appointment_date?.slice(0,10) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="start" label="预约时段" width="170">
                                <template #default="{ row }">
                                    {{row.start?.slice(0,5) + '-' + row.end?.slice(0,5) }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="hospital_name" label="医院" width="200">
                                <template #default="{ row }">
                                    {{ row.hospital_name }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="doctor_specialty" label="科室" width="140">
                                <template #default="{ row }">
                                    {{ row.doctor_specialty }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="doctor_name" label="医生" width="140">
                                <template #default="{ row }">
                                    {{ row.doctor_name }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" label="状态" width="140">
                                <template #default="{ row }">
                                    <span :class="getStatusClass(row.status)">
                                        {{ row.status }}
                                    </span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="140">
                                <template #default="{ row }">
                                    <el-button type="primary" @click="showDetail(row)" link>详情</el-button>
                                    <el-button type="danger" @click="handleCancel(row.appointment_id)" :disabled="row.status !== '待确认'" link>取消</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-dialog
                            v-model="isDetailShow"
                            title="预约详情"
                            width="350"
                            :before-close="handleClose"
                        >
                            <el-descriptions :column="1" border>
                                <el-descriptions-item label="医院">{{ detail.hospital_name }}</el-descriptions-item>
                                <el-descriptions-item label="科室">{{ detail.doctor_specialty }}</el-descriptions-item>
                                <el-descriptions-item label="医生">{{ detail.doctor_name }}</el-descriptions-item>
                                <el-descriptions-item label="日期">{{ detail.appointment_date?.slice(0,10) }}</el-descriptions-item>
                                <el-descriptions-item label="时段">{{ detail.start?.slice(0,5) +'-'+ detail.end?.slice(0,5) }}</el-descriptions-item>
                                <el-descriptions-item label="状态">{{ detail.status }}</el-descriptions-item>
                            </el-descriptions>  
                            <template #footer>
                                <div class="dialog-footer">
                                    <el-button type="primary" @click="isDetailShow = false">确认</el-button>
                                </div>
                            </template>
                        </el-dialog>
                    </div>

                    <!-- 信息修改 -->
                    <div v-if="activeIndex === '3-1'" class="settings">
                        <el-form
                        :model="editForm"
                        :rules="rules"
                        @keyup.enter="submit">
                            <el-form-item prop="name">
                                <span>姓名：</span>
                                <el-input
                                v-model="editForm.name"
                                style="width: 280px;"
                                size="default"
                                :placeholder="user.name"
                                :prefix-icon="User"/>
                            </el-form-item>
                            <el-form-item>
                                <div>性别：</div>
                                <el-select 
                                v-model="editForm.sex" 
                                style="width: 280px;"
                                :placeholder="gender"
                                :prefix-icon="Male">
                                    <el-option label="男" value="M" />
                                    <el-option label="女" value="F" />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <div>生日：</div>
                                <el-date-picker
                                style="width: 280px;"
                                v-model="editForm.birthday"
                                type="date"
                                :placeholder="moment.tz(user.birthday, 'UTC').tz('Asia/Shanghai').format('YYYY-MM-DD')"/>
                            </el-form-item>
                            <el-form-item prop="phone">
                                <div>电话：</div>
                                <el-input
                                v-model="editForm.phone"
                                style="width: 280px;"
                                size="default"
                                :placeholder="user.phone"
                                :prefix-icon="PhoneFilled"/>
                            </el-form-item>
                            <el-form-item prop="email">
                                <div>邮件：</div>
                                <el-input
                                v-model="editForm.email"
                                style="width: 280px;"
                                size="default"
                                :placeholder="user.email"
                                :prefix-icon="Message"/>
                            </el-form-item>
                            <el-form-item prop="username">
                                <div>用户名</div>
                                <el-input
                                v-model="editForm.username"
                                style="width: 280px;"
                                size="default"
                                :placeholder="user.username"
                                :prefix-icon="Avatar"/>
                            </el-form-item>
                        </el-form>
                        <el-button type="primary" @click="submit" round>提交</el-button>
                    </div>

                    <!-- 密码修改 -->
                    <div v-if="activeIndex === '3-2'" class="settings">
                        <el-form :model="form" label-width="120px" @keyup.enter="updatePassword">
                            <el-form-item label="修改密码">
                                <el-input v-model="form.oldPassword" type="password" placeholder="原密码" />
                                <el-input v-model="form.newPassword" type="password" placeholder="新密码" style="margin: 10px 0" />
                                <el-input v-model="form.confirmPassword" type="password" placeholder="确认新密码" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="updatePassword">确认修改</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { User, List, Setting, Edit, Key, Male, PhoneFilled, Message, Avatar, Back } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUser } from '@/api/getInfo'
import { getAppointInfo, cancelAppointment } from '@/api/appointment'
import { updatePwd, updateMsg } from '@/api/login'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'; // 导入 day.js

defineOptions({
    name: 'UserCenter'
})
const moment = require('moment-timezone')
const router = useRouter()

const test = ref(null)

// 详情展示
const isDetailShow = ref(false)
const loading = ref(false)
// 储存用户信息
const user = ref({})
// 信息修改表单
const editForm = ref({
    name: '',
    sex: '',
    birthday: '',
    phone: '',
    email: '',
    username: ''
})
const reset = () => {
    editForm.value = {
        name: '',
        sex: '',
        birthday: '',
        phone: '',
        email: '',
        username: ''
    }
}
// 性别格式化
const gender = computed(() => {
    return user.value.sex === 'M' ? '男' : '女'
})

// 展示的页面
const activeIndex = ref('1')

// 选择栏目
const handleSelect = (index) => {
    activeIndex.value = index
}

// 获取用户信息
async function getUserInfo() {
    const res = await getUser({
        username: sessionStorage.getItem('username')
    })
    user.value = res?.data[0] || ''
    console.log('user',user)
}

// 该用户的预约信息
const appointments = ref(null)

// 获取预约信息
async function fetchAppoint() {
    try {
        appointments.value = (await getAppointInfo({
            patient_id: sessionStorage.getItem('user_id')
        })).data
        console.log('appointments',appointments.value)
    }
    catch (error) {
        console.error('Error fetching appointments:', error)
    }
}

// 详情信息
const detail = ref(null)

// 展示详情
function showDetail(row){
    isDetailShow.value = true
    detail.value = row
}

// 取消预约
async function handleCancel(id) {
    ElMessageBox.confirm(
        '确认取消该预约嘛?',
        '取消预约',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
    .then(async () => {
        const response = await cancelAppointment({ id: id })
        console.log('response',response)
        if(!response.status) {
            // 刷新数据
            await fetchAppoint()
            ElMessage({
                type: 'success',
                message: '已取消',
            })
        } else {
            ElMessage({
                type: 'warning',
                message: response.msg
            })
        }
    })
    .catch(() => {
        ElMessage({
            type: 'info',
            message: '未取消',
        })
    })
}

// 状态样式
const getStatusClass = (status) => {
    switch (status) {
        case '待确认':
            return 'status-pending'
        case '已确认':
            return 'status-confirmed'
        case '已取消':
            return 'status-cancelled'
        default:
            return ''
    }
}

// 信息表单
// const formModel = reactive({
//     name: user.value?.name,
//     sex: gender.value,
//     birthday: user.value?.birthday,
//     phone: user.value?.phone,
//     email: user.value?.email,
//     username: user.value?.username
// })

// 信息验证
const rules = {
    name:{ pattern: /^[\u4E00-\u9FA5]+$/, message:'请输入正确姓名', trigger:'blur'},
    phone:{ pattern: /^1[3-9]\d{9}$/, message:'无效的手机号', trigger:'blur'},
    email:{ pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message:'无效的电子邮箱', trigger:'blur'},
    username:{ min: 4, max: 20, message: '用户名必须是4~20位字符', trigger:'blur'}
}

// 提交修改
async function submit(){
    const birthday_format = dayjs(editForm?.value?.birthday).format('YYYY-MM-DD'); // 格式化后的日期
    console.log('edit',editForm)
    try {
        const response = await updateMsg({
            name: editForm?.value?.name,
            sex: editForm?.value?.sex,
            birthday: editForm?.value?.birthday,
            phone: editForm?.value?.phone,
            email: editForm?.value?.email,
            username: editForm?.value?.username,
            user_id: sessionStorage.getItem('user_id')
        })
        if(response.status) {
            ElMessage.warning(response.msg)
        } else {
            ElMessage.success(response.msg)
            getUserInfo()
            reset()
        }
    } catch { }
}

// 密码表单
const form = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

// 修改密码
const updatePassword = async () => {
    if (!form.oldPassword || !form.newPassword || !form.confirmPassword) {
        ElMessage.warning('请填写完整信息')
        return
    }
    if (form.newPassword !== form.confirmPassword) {
        ElMessage.error('两次输入的密码不一致')
        return
    }
    const response = await updatePwd({
        pre_pwd: form.oldPassword,
        password: form.newPassword,
        passwordDb: form.confirmPassword,
        user_id: sessionStorage.getItem('user_id')
    })
    if(response.status) {
        return ElMessage.error(response.msg)
    } else {
        ElMessage.success('修改成功')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('auth')
        sessionStorage.removeItem('username')
        sessionStorage.removeItem('user_id')
        router.replace('/login')
        ElMessage.warning('身份过期，请重新登录')
    }
}

// 返回首页
function backToHome() {
    router.back()
}

onMounted(() => {
    getUserInfo()
    fetchAppoint()
})

</script>

<style lang="scss" scoped>
.user-center {
    padding: 20px;
    min-height: calc(100vh - 70px);
    background-color: #f5f7fa;

    .el-container {
        background-color: #fff;
        border-radius: 4px;
        min-height: calc(100vh - 110px);
    }

    .el-aside {
        border-right: 1px solid #e6e6e6;
        overflow: hidden;

        .back {
            padding: 0 20px;
            font-size: 20px;
            font-weight: 100;
        }
        
        .menu {
            height: 100%;
        }
    }

    .el-main {
        padding: 20px;

        .content {
            .profile {
                padding: 20px;
            }

            .appointments {
                padding: 20px;

                .status-pending {
                    color: #409EFF;
                }

                .status-confirmed {
                    color: #67C23A;
                }

                .status-cancelled {
                    color: #F56C6C;
                }
            }

            .settings {
                max-width: 500px;
                padding: 20px;
            }
        }
    }
}
</style>
